<?php
App::uses('AppController', 'Controller');
/**
 * UserOrders Controller
 *
 * @property UserOrder $UserOrder
 * @property PaginatorComponent $Paginator
 */
class UserOrdersController extends AppController {

/**
 * Components
 *
 * @var array
 */
	public $components = array('Paginator');

	
	public function beforeFilter() {
		$this->Auth->allow('add','cpay','gotopay','success','callback');
		parent::beforeFilter();
	}
	
/**
 * index method
 *
 * @return void
 */
	public function index() {
		$this->UserOrder->recursive = 0;
		
		$this->Paginator->settings = array(
				'conditions'=>	array(
					'UserOrder.user_id'=>$this->Auth->user('id')
				),
				'order'=>'UserOrder.created DESC',
				'limit'=>7
		);
		
		$this->set('userOrders', $this->Paginator->paginate('UserOrder'));
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		if (!$this->UserOrder->exists($id)) {
			throw new NotFoundException(__('Invalid user order'));
		}
		$this->UserOrder->recursive = 2;
		$options = array('conditions' => array('UserOrder.' . $this->UserOrder->primaryKey => $id));
		$this->set('userOrder', $this->UserOrder->find('first', $options));
	}

/**
 * add method
 *
 * @return void
 */
	public function add() {
		$cart = $this->Session->read(Configure::read("Cart.SessionKey"));
		if(!$cart || $cart['count'] == 0){
			if($this->request->isAjax()){
				$this->set('state',false);
				$this->set('msg','购物车为空');
				$data = array(
						'order_id' =>0,
						'redirect' =>citylink('Carts','view','cart')
				);
				$this->set('data',$data);
			}else{
				$this->Session->setFlash(__('购物车为空'),'tip/tip_uc');
				$this->redirect(citylink('Carts','view','cart'));
			}
		}else{
			$this->set('carts',$cart);
		}		
		if ($this->request->is('post')) {
			$this->UserOrder->create();
			$this->request->data['UserOrder']['user_id'] = $this->Auth->user('id');
			$this->request->data['UserOrder']['sys_website_id'] = Configure::read('SITEID');
			if(isset($this->request->data['UserOrder']['seat'])){
				$res =$this->UserOrder->createSeatOrder($this->request->data);
				$return = $res['state'];
			}else{
				$return =$this->UserOrder->createOrder($this->request->data);
				$res = array('state'=>$return,'msg'=>'保存失败');
			}
			//createSeatOrder
			if ($return) {
				$this->set('state',true);
				if($this->request->data['UserOrder']['sys_paytype_id']==1){  //网上支付
					$redirect = 'UserOrders/cpay/'.$this->UserOrder->id;
				}else{													
					$redirect = 'UserOrders/success/'.$this->UserOrder->id;
				}
				
				$data = array(
					'order_id' =>$this->UserOrder->id,
					'redirect' =>$redirect
				);
				$this->set('data',$data);
				$this->Session->delete(Configure::read("Cart.SessionKey"));
			} else {
				$this->set('state',false);
				$this->set('msg',$res['msg']);
			}
			$this->set('html','');
		}else{
		
			//配送方式----------------------------------------------
			$this->loadModel('SysGettype');
			$sysGettypes = $this->SysGettype->find('list');
			$this->set('sysGettypes',$sysGettypes);
			
			//支付方式----------------------------------------------
			$this->loadModel('SysPaytype');
			$sysPaytypes = $this->SysPaytype->find('all');
			$this->set('sysPaytypes',$sysPaytypes);
			//收货地址----------------------------------------------
			$this->loadModel('SysArea');
			if($this->Auth->user()){
				$this->loadModel('UserAddress');
				$address = $this->UserAddress->find('all',array('conditions'=>array('UserAddress.users_id'=>$this->Auth->user('id'))));
			}else{
				$address = $this->Session->read('noaddress');	
			}
			$sysProvinces = $this->SysArea->find('list',array(
					'conditions'=>array(
							'SysArea.parent_id'=>139
					)
			));
			$sysCity = $this->SysArea->find('list',array(
					'conditions'=>array(
							'SysArea.parent_id'=>784
					)
			));
			$this->set('sysProvinces',$sysProvinces);
			$this->set('sysCitys',$sysCity);
			$this->set('address',$address);
			
		}
		
		if($cart['seat']){
			$this->render('add_seat');
		}
		
		$this->set('seo_title','订单信息');
		$this->set('seo_keywords',false);
		$this->set('seo_description',false);
		$this->set('seo_title_ext','【秦文票务演出订票官网】');
	}
	
	/**
	 * 网银支付 支付方式
	 * @author mingxing.zhao@qq.com
	 * @date 2014-5-3 下午7:26:18
	 * @param variable
	 * @return 
	 */
	public function cpay($order_id,$pay_type_id = false) {
		$userOrder = $this->UserOrder->findById($order_id);
		
		if($userOrder['UserOrder']['user_order_state_id']!=1){
			$this->redirect(array('action'=>'success',$order_id));
		}
		
		$this->set('userOrder',$userOrder);
		
		$this->set('seo_title','确认支付');
		$this->set('seo_keywords',false);
		$this->set('seo_description',false);
		$this->set('seo_title_ext','【秦文票务演出订票官网】');
	}
	
	public function success($order_id) {
		$userOrder = $this->UserOrder->findById($order_id);
		$this->set('userOrder',$userOrder);
		
		$this->set('seo_title','下单成功');
		$this->set('seo_keywords',false);
		$this->set('seo_description',false);
		$this->set('seo_title_ext','【秦文票务演出订票官网】');
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		if (!$this->UserOrder->exists($id)) {
			throw new NotFoundException(__('Invalid user order'));
		}
		if ($this->request->is(array('post', 'put'))) {
			if ($this->UserOrder->save($this->request->data)) {
				$this->Session->setFlash(__('The user order has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user order could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('UserOrder.' . $this->UserOrder->primaryKey => $id));
			$this->request->data = $this->UserOrder->find('first', $options);
		}
		$sysWebsites = $this->UserOrder->SysWebsite->find('list');
		$users = $this->UserOrder->User->find('list');
		$userOrderStates = $this->UserOrder->UserOrderState->find('list');
		$userAddresses = $this->UserOrder->UserAddress->find('list');
		$sysGettypes = $this->UserOrder->SysGettype->find('list');
		$sysLogisticTpls = $this->UserOrder->SysLogisticTpl->find('list');
		$sysPaytypes = $this->UserOrder->SysPaytype->find('list');
		$userOrderPaytypes = $this->UserOrder->UserOrderPaytype->find('list');
		$this->set(compact('sysWebsites', 'users', 'userOrderStates', 'userAddresses', 'sysGettypes', 'sysLogisticTpls', 'sysPaytypes', 'userOrderPaytypes'));
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$this->UserOrder->id = $id;
		if (!$this->UserOrder->exists()) {
			throw new NotFoundException(__('Invalid user order'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->UserOrder->delete()) {
			$this->Session->setFlash(__('The user order has been deleted.'));
		} else {
			$this->Session->setFlash(__('The user order could not be deleted. Please, try again.'));
		}
		return $this->redirect(array('action' => 'index'));
	}

/**
 * admin_index method
 *
 * @return void
 */
	public function admin_index() {
		$this->UserOrder->recursive = 0;
		$action = array('admin' => true,'controller' => 'UserOrders','action'=>'jsonPage');
		$param = $this->UserOrder->pageParam($action);
		$this->set('paginationScript',$this->UserOrder->showGridPagination($param));
		$userOrderStates = $this->UserOrder->UserOrderState->find('list');
		$this->set('userOrderStates', $userOrderStates);
	}
	
	/**
	 * function
	 * @author mingxing.zhao@qq.com
	 * @date 2013-12-21 下午5:05:53
	 * @param variable
	 * @return
	 */
	function admin_jsonPage($type = false){
		$this->UserOrder->recursive = 0;
		$this->autoRender = false;
		$searchtype = $this->request->data('_search');
		$conditions = array('UserOrder.user_order_state_id <'=>5);
		$conditions = array();
		if($searchtype=='true'){
			$conditions = $this->search_condition($this->request->data);
		}
		
		$conditions['UserOrder.sys_website_id']= $this->Session->read('SITEID');
	
		$config = array(
				'_search'=>$searchtype,
				'page'=>$this->request->data('page'),
				'rows'=>$this->request->data('rows'),
				'sidx'=>$this->request->data('sidx'),
				'sord'=>$this->request->data('sord')
		);
		$res = $this->UserOrder->pagination($config,array(),$conditions,2);
		return $this->UserOrder->jsonData($res);
	}
	
	public function admin_TicetckAC(){
		$keyword = trim($this->request->query['keyword']);
		$SITEID = $this->Session->read('SITEID');
		$this->loadModel('Ticket');
		$this->Ticket->recursive = -1;
		$tickets = $this->Ticket->find('all',array(
				'fields'=>array('Ticket.id','Ticket.title'),
				'conditions'=>array(
						'Ticket.sys_website_id'=>$SITEID,
						'Ticket.title like'=>'%'.$keyword.'%'
				),
				'limit'=>10,
				'order'=>array('Ticket.created DESC')
		));
		//-----------------------------------------------
		$data = array();
		foreach ($tickets as $item){
			$data[] = array(
					'id'=>$item['Ticket']['id'],
					'label'=>$item['Ticket']['title'],
			);
		}
		$this->set('data',$data);
		$this->set('state',true);
		$this->render(false);
	}
	
	/**
	 * 查询条件
	 * @author zmx@gootop.net
	 * @Date 2011-2-23
	 * @return
	 */
	private function search_condition($param){
		$this->UserOrder->recursive = 0;
		$search['UserOrder'] = $param['UserOrder'];
		$c = $this->postConditions($search);
		$return = array();
		if($c['UserOrder.id'] != ''){
				return	array('UserOrder.id' =>$c['UserOrder.id']);
		}
		
		if($c['UserOrder.user_order_state_id'] > 0){
			$return['UserOrder.user_order_state_id']= $c['UserOrder.user_order_state_id'];
		}else{
			$return['UserOrder.user_order_state_id <'] = 5;
		}
		
		if($c['UserOrder.address_phone'] != ''){
			$return['UserOrder.address_phone']= $c['UserOrder.address_phone'];
		}
		
		if(isset($param['Ticket']['id']) && $param['Ticket']['id']!=''){
			$oids = $this->UserOrder->UserOrderList->find('list',array(
				'fields'=>array('UserOrderList.id','UserOrderList.user_order_id'),
				'conditions'=>array('UserOrderList.ticket_id'=>$param['Ticket']['id'])
			));
			$return['UserOrder.id'] = array_unique($oids);
		}
		
		if($c['UserOrder.from'] !='' && $c['UserOrder.to'] !=''){
			$return['AND']['UserOrder.created >=']= $c['UserOrder.from'];
			$return['AND']['UserOrder.created <=']= $c['UserOrder.to'].' 23:59:59';
		}else if($c['UserOrder.from'] !=''){
			$return['UserOrder.created >=']= $c['UserOrder.from'];
		}else if($c['UserOrder.to'] !=''){
			$return['UserOrder.created <=']= $c['UserOrder.to'].' 23:59:59';
		}
		
		return $return;
	}

/**
 * admin_view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_view($id = null) {
		if (!$this->UserOrder->exists($id)) {
			throw new NotFoundException(__('Invalid user order'));
		}
		$this->UserOrder->recursive = 2;
		$options = array('conditions' => array('UserOrder.' . $this->UserOrder->primaryKey => $id));
		$this->set('userOrder', $this->UserOrder->find('first', $options));
		$userOrderStates = $this->UserOrder->UserOrderState->find('list');
		$this->set('userOrderStates', $userOrderStates);
	}

/**
 * admin_add method
 *
 * @return void
 */
	public function admin_add() {
		if ($this->request->is('post')) {
			$this->UserOrder->create();
			if ($this->UserOrder->save($this->request->data)) {
				$this->Session->setFlash(__('The user order has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user order could not be saved. Please, try again.'));
			}
		}
		$sysWebsites = $this->UserOrder->SysWebsite->find('list');
		$users = $this->UserOrder->User->find('list');
		$userOrderStates = $this->UserOrder->UserOrderState->find('list');
		$userAddresses = $this->UserOrder->UserAddress->find('list');
		$sysGettypes = $this->UserOrder->SysGettype->find('list');
		$sysLogisticTpls = $this->UserOrder->SysLogisticTpl->find('list');
		$sysPaytypes = $this->UserOrder->SysPaytype->find('list');
		$userOrderPaytypes = $this->UserOrder->UserOrderPaytype->find('list');
		$this->set(compact('sysWebsites', 'users', 'userOrderStates', 'userAddresses', 'sysGettypes', 'sysLogisticTpls', 'sysPaytypes', 'userOrderPaytypes'));
	}

/**
 * admin_edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_edit($id = null) {
		if (!$this->UserOrder->exists($id)) {
			throw new NotFoundException(__('Invalid user order'));
		}
		if ($this->request->is(array('post', 'put'))) {
			if ($this->UserOrder->save($this->request->data)) {
				$this->Session->setFlash(__('The user order has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user order could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('UserOrder.' . $this->UserOrder->primaryKey => $id));
			$this->request->data = $this->UserOrder->find('first', $options);
		}
		$sysWebsites = $this->UserOrder->SysWebsite->find('list');
		$users = $this->UserOrder->User->find('list');
		$userOrderStates = $this->UserOrder->UserOrderState->find('list');
		$userAddresses = $this->UserOrder->UserAddress->find('list');
		$sysGettypes = $this->UserOrder->SysGettype->find('list');
		$sysLogisticTpls = $this->UserOrder->SysLogisticTpl->find('list');
		$sysPaytypes = $this->UserOrder->SysPaytype->find('list');
		$userOrderPaytypes = $this->UserOrder->UserOrderPaytype->find('list');
		$this->set(compact('sysWebsites', 'users', 'userOrderStates', 'userAddresses', 'sysGettypes', 'sysLogisticTpls', 'sysPaytypes', 'userOrderPaytypes'));
	}

	
	public function admin_logistic($id) {
		if (!$this->UserOrder->exists($id)) {
			throw new NotFoundException(__('Invalid user order'));
		}
		if ($this->request->is(array('post', 'put'))) {
			$this->request->data['UserOrder']['user_order_state_id'] = 3;
			if($this->request->data['UserOrder']['logisticnum'] == ''){
				$this->Session->setFlash(__('物流单号不能为空'),'tip/tip_float',array('t'=>'error'));
			}else if ($this->UserOrder->save($this->request->data)) {
				$this->Session->setFlash(__('物流单号'),'tip/tip_float',array('t'=>'success'));
			} else {
				$this->Session->setFlash(__('更新失败 请重试'),'tip/tip_float',array('t'=>'error'));
			}
		} 
		return $this->redirect(array('action' => 'view',$id));
	}
	
	public function admin_state($id) {
		if (!$this->UserOrder->exists($id)) {
			throw new NotFoundException(__('Invalid user order'));
		}
		if ($this->request->is(array('post', 'put'))) {
			if ($this->UserOrder->save($this->request->data)) {
				$this->Session->setFlash(__('订单状态已更新'),'tip/tip_float',array('t'=>'success'));
			} else {
				$this->Session->setFlash(__('更新失败 请重试'),'tip/tip_float',array('t'=>'error'));
			}
		}
		return $this->redirect(array('action' => 'view',$id));
	}
/**
 * admin_delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_delete($id = null) {
		$this->UserOrder->id = $id;
		if (!$this->UserOrder->exists()) {
			throw new NotFoundException(__('Invalid user order'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->UserOrder->delete()) {
			$this->Session->setFlash(__('The user order has been deleted.'));
		} else {
			$this->Session->setFlash(__('The user order could not be deleted. Please, try again.'));
		}
		return $this->redirect(array('action' => 'index'));
	}
	
	public function admin_pubeticket($user_order_list_id = false,$user_order_id = false){
			if(!$user_order_list_id) return;
			$this->loadModel('Qrcodeing');
			$hash = encodeET($user_order_list_id);
			$url = Router::url(array('admin'=>false,'controller'=>'Index','action'=>'eticket',$hash),true);
			$this->Qrcodeing->createQRCode($user_order_list_id,$url);
			$this->Qrcodeing->getET($user_order_list_id);
			$this->UserOrder->UserOrderList->id = $user_order_list_id;
			$this->UserOrder->UserOrderList->set('state',2);
			$this->UserOrder->UserOrderList->save();
			$this->Session->setFlash(__('电子票已生成'),'tip/tip_float',array('t'=>'success'));
			return $this->redirect(array('action' => 'view',$user_order_id));
	}

}